package com.health.platform.provider.diseasemonitoring.service;

import com.health.platform.common.restful.AppResponse;
import com.health.platform.provider.diseasemonitoring.dao.InfectionDao;
import com.health.platform.provider.diseasemonitoring.entity.DiseaseEntity;
import com.health.platform.provider.diseasemonitoring.entity.InfectionEntity;
import com.health.platform.provider.diseasemonitoring.entity.WarningEntity;
import com.health.platform.common.core.entity.EchartsEntity;
import com.health.platform.common.utils.MyUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>病症监控-传染病监控预警_地方</p>
 * <p>创建日期：2021-02-27</p>
 *
 * @author wangyanlei
 */
@Service
public class InfectionService {

    @Resource
    private InfectionDao infectionDao;

    /**
     * 获取中间部分汇总信息
     * 1.报告发病人数、同比
     * 2.报告死亡人数、同比
     * 3.报告发病率、同比
     * 4.报告死亡率、同比
     *
     * @param infectionEntity 参数
     * @return 结果
     */
    public AppResponse getPersonTotal(InfectionEntity infectionEntity) {
        Map<String, Object> result = new HashMap<>(8);
        //  ——————————————————————1.报告发病人数、同比 ——————————————————————
        String[] targetType = new String[]{"GW_TYPE29"};
        infectionEntity.setTargetTypeArr(targetType);
        // 页面选择的日期
        infectionEntity.getConditionAreaStr();
        Integer thisYearGetInfection = infectionDao.getTargetGWTable(infectionEntity);
        thisYearGetInfection = thisYearGetInfection == null ? 0 : thisYearGetInfection;
        result.put("thisYearGetInfection", thisYearGetInfection);
        // 去年同期
        infectionEntity.setCompare(true);
        Integer lastYearGetInfection = infectionDao.getTargetGWTable(infectionEntity);
        lastYearGetInfection = lastYearGetInfection == null ? 0 : lastYearGetInfection;
        // 计算同比
        String infectionProportion = MyUtils.getProportion(thisYearGetInfection, lastYearGetInfection);
        result.put("infectionProportion", infectionProportion);
        //  ——————————————————————2.报告死亡人数、同比 ——————————————————————
        targetType = new String[]{"GW_TYPE30"};
        infectionEntity.setTargetTypeArr(targetType);
        infectionEntity.setCompare(false);
        // 页面选择的日期
        Integer thisYearDeath = infectionDao.getTargetGWTable(infectionEntity);
        thisYearDeath = thisYearDeath == null ? 0 : thisYearDeath;
        result.put("thisYearDeath", thisYearDeath);
        // 去年同期
        infectionEntity.setCompare(true);
        Integer lastYearDeath = infectionDao.getTargetGWTable(infectionEntity);
        lastYearDeath = lastYearDeath == null ? 0 : lastYearDeath;
        // 计算同比
        String deathProportion = MyUtils.getProportion(thisYearDeath, lastYearDeath);
        result.put("deathProportion", deathProportion);
        //  ——————————————————————3.报告发病率、同比 ——————————————————————
        // 今年常住人口
        String[] oftenPeople = new String[]{"ZB_TYPE2"};
        infectionEntity.setTargetTypeArr(oftenPeople);
        infectionEntity.setCompare(false);
        Integer oftenPeopleTotal = infectionDao.getTargetZBTable(infectionEntity);
        oftenPeopleTotal = oftenPeopleTotal == null ? 0 : oftenPeopleTotal;
        // 今年发病率
        String thisGetRate = MyUtils.getRate(thisYearGetInfection, oftenPeopleTotal);
        result.put("thisGetRate", thisGetRate);
        // 发病率同比
        // 去年发病率
        infectionEntity.setCompare(true);
        Integer lastOftenPeopleTotal = infectionDao.getTargetZBTable(infectionEntity);
        lastOftenPeopleTotal = lastOftenPeopleTotal == null ? 0 : lastOftenPeopleTotal;
        String lastGetRate = MyUtils.getRate(lastYearGetInfection, lastOftenPeopleTotal);
        String infectionRateProportion = MyUtils.getProportion((int)(Double.parseDouble(thisGetRate)*100), (int)(Double.parseDouble(lastGetRate)*100));
        result.put("infectionRateProportion", infectionRateProportion);

        //  ——————————————————————4.报告死亡率、同比 ——————————————————————
        // 今年死亡率
        String thisDeathRate = MyUtils.getRate(thisYearDeath, thisYearGetInfection);
        result.put("thisDeathRate", thisDeathRate);
        // 去年死亡率
        infectionEntity.setCompare(true);
        String lastDeathRate = MyUtils.getRate(lastYearDeath, lastYearGetInfection);
        // 死亡率同比
        String deathRateProportion = MyUtils.getProportion((int)(Double.parseDouble(thisDeathRate)*100), (int)(Double.parseDouble(lastDeathRate)*100));
        result.put("deathRateProportion", deathRateProportion);
        return AppResponse.success("查询成功", result);
    }

    /**
     * 获取中间部分汇总信息
     * 5.传染病病种排名
     * 7.传染病人群分布
     * 8.传染病人群职业分布
     * 9、新冠重点区域来我域人数排名
     *
     * @param infectionEntity 参数
     * @return 结果
     */
    public AppResponse getEchartsData(InfectionEntity infectionEntity) {
        Map<String, Object> result = new HashMap<>(8);
        //  ——————————————————————5.传染病病种排名 ——————————————————
        // 低收入人口疾病排名
        List<EchartsEntity> kindSort = infectionDao.getKindSort(infectionEntity);
        result.put("kindSort",kindSort);
        //  ——————————————————————7.传染病人群分布——————————————————
        List<EchartsEntity> ageSort = infectionDao.getAgeSort(infectionEntity);
        result.put("ageSort",ageSort);
        //  ——————————————————————8.传染病人群职业分布——————————————————
        List<EchartsEntity> jobSort = infectionDao.getJobSort(infectionEntity);
        result.put("jobSort",jobSort);
        return AppResponse.success("查询成功", result);
    }

    /**
     * 6.传染病报告人数趋势
     * 折线图：按传染病病种发现人数的时间趋势（按日<近7日>、周<近12周>、月<近12个月>、年<近5年>）；去年同期；平均值线
     * @param infectionEntity 参数
     * @return 结果
     */
    public AppResponse getLineChart(InfectionEntity infectionEntity) {
        //  ——————————————————————6.传染病报告人数趋势—————————————————
        Map<String, Object> result = new HashMap<>(2);
        // 指定日期趋势
        List<EchartsEntity> thisMap=infectionDao.getLineByDate(infectionEntity);
        thisMap = MyUtils.getEchartsDataByYear(thisMap,infectionEntity.getRecentYearArr());
        // 指定日期 的同期趋势
        infectionEntity.setCompare(true);
        List<EchartsEntity> lastMap=infectionDao.getLineByDate(infectionEntity);
        lastMap = MyUtils.getEchartsDataByYear(lastMap,infectionEntity.getRecentYearCompareArr());
        result.put("thisMap",thisMap);
        result.put("lastMap",lastMap);
        return AppResponse.success("查询成功", result);
    }

    /**
     * 根据传染病code 换取中文名称
     *
     * @param map 参数
     * @return 结果
     */
    /*private Map<String, String> getDesc(Map<String, EchartsEntity> map) {
        Map<String, String> returnMap = new HashMap<>(10);
        for (String key : map.keySet()) {
            String newKey = infectionDao.getKeyDesc(key);
            String newValue = map.get(key).getValue();
            returnMap.put(newKey, newValue);
        }
        return returnMap;
    }*/
    /**
     * 查询码表
     *
     * @param
     * @return 结果
     * @author shi_xy_sr@neusiri.com
     * @date 2021/3/4 17:23
     */
    public AppResponse getDict() {
        return AppResponse.success("查询成功", infectionDao.getDict());
    }

    /**
     * 按条件获取传染病预警信息，并插入到预警历史表
     *
     * @param
     * @return 结果
     * @author shi_xy_sr@neusiri.com
     * @date 2021/3/10 16:24
     */
    public AppResponse getWarning(DiseaseEntity diseaseEntity) {
        Map<String, Object> result = new HashMap<>();
        int insertTotal = 0;
        //一、查询当前传染病预警记录表，最后一条预警的预警id和时间
        List<DiseaseEntity> history = infectionDao.getWarningHistory();
        String id = "1";//新预警的id
        Date historyTime = null;//最后一条预警的时间
        if (history.size() >0){
            id = Integer.parseInt(history.get(0).getId()) + 1 + "";//最新一条的id+1
            historyTime = history.get(0).getWarningtime();
        }
        //二、查询当前时间之前，上次的传染病预警时间之后，符合条件的病例信息
        diseaseEntity.setWarningtime(historyTime);
        Map<String, Object> warningMap = getWarnByCondition(diseaseEntity);
        //此处先查询一级预警
        String[] diseasecodeArr = new String[]{"010100","010200"};
        diseaseEntity.setDiseasecodeArr(diseasecodeArr);
        List<WarningEntity> warningList = (List<WarningEntity>)warningMap.get("warning");
        //二.1 若有预警，保存预警历史表，预警时间是最后一条病例的报告时间
        if(warningList.size() >0){
            Date warningTime =warningList.get(warningList.size()-1).getReportdate();
            for (WarningEntity warning : warningList){
                DiseaseEntity dieease = new DiseaseEntity();
                dieease.setId(id);//预警记录id
                dieease.setWarningtime(warningTime);//预警时间
                dieease.setCardCode(warning.getCardCode());//传染病报卡编号
                dieease.setDiseasename(warning.getDiseasename());//预警内容
                dieease.setWarninglive(warning.getWarninglive());
                dieease.setRemark("0");
                insertTotal += infectionDao.insertWaringRecord(dieease);
            }
        }
        if (insertTotal > 0 ){
            result.put("message","预警病例"+ insertTotal + "例");
        }else{
            result.put("message","没有病例满足预警条件");
        }
        //三、查询当前预警返回前台
        diseaseEntity.setRemark("0");
        List<DiseaseEntity> warningnowList = infectionDao.getWarningHistoryInfo(diseaseEntity);
        //TODO 多来两条返回前台 到时候注解掉
        List<DiseaseEntity> warningnowList2 = new ArrayList<DiseaseEntity>();
        warningnowList2.addAll(warningnowList);
        warningnowList2.addAll(warningnowList);
        warningnowList2.addAll(warningnowList);
        result.put("warningList",warningnowList2);
        result.put("warningCount",warningnowList2.size());
        //result.put("warningList",warningnowList);
        //result.put("warningCount",warningnowList.size());
        return AppResponse.success("查询成功", result);
    }
    /**
     * 根据预警规则获取判断是否有病例
     *
     * @param
     * @return 结果
     * @author shi_xy_sr@neusiri.com
     * @date 2021/3/12 10:59
     */
    private Map<String, Object> getWarnByCondition(DiseaseEntity diseaseEntity) {
        Map<String, Object> result = new HashMap<>();
        List<WarningEntity> warning = new ArrayList<WarningEntity>();
        //----------------------一级预警----------------------
        diseaseEntity.setDiseasename("甲类传染病预警");
        diseaseEntity.setWarninglive("1");
        String[] diseasecodeArr = new String[]{"010100","010200"};
        diseaseEntity.setDiseasecodeArr(diseasecodeArr);
        warning.addAll(infectionDao.getWarning(diseaseEntity));
        //----------------------二级预警----------------------
        diseaseEntity.setDiseasename("");
        diseaseEntity.setWarninglive("2");
        //----------------------三级预警----------------------
        diseaseEntity.setDiseasename("");
        diseaseEntity.setWarninglive("3");
        //----------------------四级预警----------------------
        diseaseEntity.setDiseasename("");
        diseaseEntity.setWarninglive("4");

        result.put("warning",warning);
        return result;
    }

    /**
     * 获取历史传染病预警信息
     *
     * @param
     * @return 结果
     * @author shi_xy_sr@neusiri.com
     * @date 2021/3/12 9:03
     */
    public AppResponse getWarningHistory(DiseaseEntity diseaseEntity) {
        Map<String, Object> result = new HashMap<>();
        diseaseEntity.setRemark("1");
        List<DiseaseEntity> historyList = infectionDao.getWarningHistoryInfo(diseaseEntity);
        result.put("historyList",historyList);
        return AppResponse.success("查询成功", result);
    }
    /**
     * 更新预警信息为已查看
     *
     * @param
     * @return 结果
     * @author shi_xy_sr@neusiri.com
     * @date 2021/3/12 9:04
     */
    public AppResponse lookWarning(DiseaseEntity diseaseEntity) {
        Map<String, Object> result = new HashMap<>();
        int updateCount = infectionDao.updateWaringRemark(diseaseEntity);
        String message = "无可更新数据";
        if (updateCount > 0 ){
            message = "更新成功";
        }
        return AppResponse.success(message);
    }
}
